#!/usr/bin/php
<?php
require_once 'Classes/phpICQ.Classes.php';
include_once 'config.inc.php';

function arguments($args ) {
    $ret = array(
        'exec'      => '',
        'options'   => array(),
        'flags'     => array(),
        'arguments' => array(),
    );

    $ret['exec'] = array_shift( $args );

    while (($arg = array_shift($args)) != NULL) {
        // Is it a option? (prefixed with --)
        if ( substr($arg, 0, 2) === '--' ) {
            $option = substr($arg, 2);

            // is it the syntax '--option=argument'?
            if (strpos($option,'=') !== FALSE)
                array_push( $ret['options'], explode('=', $option, 2) );
            else
                array_push( $ret['options'], $option );
           
            continue;
        }

        // Is it a flag or a serial of flags? (prefixed with -)
        if ( substr( $arg, 0, 1 ) === '-' ) {
            for ($i = 1; isset($arg[$i]) ; $i++)
                $ret['flags'][] = $arg[$i];

            continue;
        }

        // finally, it is not option, nor flag
        $ret['arguments'][] = $arg;
        continue;
    }
    return (object)$ret;
}//function arguments
$argv = $argv;

//print_r( arguments( $argv ) );

$help = 
"
PHP ICQ agent control.

Help: 
  restart - restart agent 
  stop    - stop agent
  
";

if (count($argv) == 1) {
    echo $help;
} else {
    $args = arguments($argv);
    $val = array_values($args->arguments);
    
    $restart = (array_search("restart", $val) !== false);
    $stop    = (array_search("stop", $val) !== false);
    $start    = (array_search("start", $val) !== false);
    if ($restart) {
        echo " * External restart flag is set.\n";
        file_put_contents($fileRestartFlag, "0");
    } elseif ($stop) {
        echo " * Stoping server.\n";
        phpICQ_settings::ServerStatusBase(new phpICQ_baseConnection($dsn), "0");
    } elseif ($start) {
        echo " * Server may be started.\n";
        phpICQ_settings::ServerStatusBase(new phpICQ_baseConnection($dsn), "1");
    } else {
        echo $help;
    }
}

?>
